package moodish.comm;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * This class represents a Thread that will handle the messages received from the server.
 * 
 * @author Filipe Afonso, Tiago Ribeiro
 * @version 1.0
 */


public class DealWithServer extends Thread {
	
	private Socket socket;
	private ObjectInputStream in;
	private LinkedBlockingQueue<MoodishClientSideMessage>  incomingMessages;
	
	/**
	 * Construct's a new {@link DealWithServer} thread.
	 * 
	 * @param socket, the socket created to handle the communication with the server.
	 * @param incomingMessages, the client list of  incoming messages from the server.
	 */
	

	public DealWithServer(Socket socket,
			LinkedBlockingQueue<MoodishClientSideMessage> incomingMessages) {
		assert incomingMessages !=null;
		assert socket != null;
		assert !socket.isClosed() && socket.isBound();
		
		this.socket = socket;
		this.incomingMessages = incomingMessages;
	}

	/**
	 * This method starts the thread. Its main objective is to receive messages 
	 * from the server and pass it along to the client, by putting said message in a
	 * {@link LinkedBlockingQueue} {@code incomingMessages}.
	 */
	
	@Override
	public void run() {
		try {
			in = new ObjectInputStream(socket.getInputStream());
			while (socket.isConnected()) {
				incomingMessages.put((MoodishClientSideMessage) in.readObject());
			}

		} catch (IOException e) {
			//TODO
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				socket.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}